
package dieci.database.rawmaterial;

import dieci.database.PersistentObject;
import dieci.database.SessionFactoryUtil;
import dieci.hibernate.HibRawMaterial;
import dieci.hibernate.HibRawMaterialProduct;
import dieci.managers.rawmaterial.RawMaterialProductManager;
import dieci.system.RawMaterial;
import dieci.system.RawMaterialProduct;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author DuckSys
 */
public class RawMaterialHibernateDAO implements RawMaterialDAO
{
    private static Logger logger = Logger.getLogger("RawMaterialHibernateDAO.log");
    
    @Override
    public List<RawMaterial> list()
    {
        List<RawMaterial> rawMaterials = new ArrayList<>();

        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibRawMaterial> hibRawMaterials = session.createCriteria(HibRawMaterial.class).
                    add(Restrictions.eq("deleted", 0)).list();
            for (HibRawMaterial dbRawMaterial : hibRawMaterials) {
                RawMaterial material = new RawMaterial(dbRawMaterial.getRawMaterialId(),
                        dbRawMaterial.getName(), dbRawMaterial.getMessureUnit(), 
                        dbRawMaterial.getAmount(), dbRawMaterial.getPrice(), dbRawMaterial.getDeleted());
                rawMaterials.add(material);
            }

            return rawMaterials;
        }
        catch (Exception e) {

            logger.log(Level.INFO, "Error listando materialentes", e.getMessage());

            throw new IllegalStateException("Error al listar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

    }

    @Override
    public List<RawMaterial> findByMaterialName(String name)
    {
        List<RawMaterial> result = new ArrayList<>();
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibRawMaterial> hibRawMaterialList = session.createCriteria(HibRawMaterial.class).
                    add(Restrictions.like("name", name + "%")).
                    add(Restrictions.eq("deleted", 0)).list();
            for (HibRawMaterial hibRawMaterial : hibRawMaterialList)
            {
                result.add(new RawMaterial(hibRawMaterial.getRawMaterialId(), 
                        hibRawMaterial.getName(), hibRawMaterial.getMessureUnit(), 
                        hibRawMaterial.getAmount(), hibRawMaterial.getPrice(), hibRawMaterial.getDeleted()));
            }



        }
        catch (Exception e) {
            throw new IllegalStateException("Error al buscar por nombre",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

        return result;

    }

    @Override
    public void saveOrUpdate(PersistentObject object)
    {
        Session session = null;

        RawMaterial material = (RawMaterial) object;
        RawMaterial found = findById(material.getRawMaterialId());
        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();
            
            session.beginTransaction();

            if (found != null) 
            {
                //UPDATE
                material.setRawMaterialId(found.getRawMaterialId());
               
                HibRawMaterial hibRawMaterial = new HibRawMaterial(material.getRawMaterialId(), (RawMaterial) material);
                session.saveOrUpdate(hibRawMaterial);

            }
            else 
            {
                //NEW
                HibRawMaterial hibRawMaterial = new HibRawMaterial(material);

                // generate new id
                session.save(hibRawMaterial);
                
            }

            session.getTransaction().commit();

        }
        catch (Exception e) {
            if(session!=null){
                session.getTransaction().rollback();
            } 
            throw new IllegalStateException("Error al guardar o actualizar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    
    }

    @Override
    public void delete(PersistentObject object)
    {
        Session session = null;

        RawMaterial material = (RawMaterial) object;
        RawMaterial found = findById(material.getRawMaterialId());
        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();
            
            session.beginTransaction();

            if (found != null) 
            {
                //UPDATE the deleted column
                material.setRawMaterialId(found.getRawMaterialId());
               
                HibRawMaterial hibRawMaterial = new HibRawMaterial(material.getRawMaterialId(), 
                        (RawMaterial) material);
                
                //DELETE FROM MATERIA_PRIMA_PRODUCTO
                RawMaterialProductManager rawMatProduct = new RawMaterialProductManager();
                List<RawMaterialProduct> rawMatProdList = rawMatProduct.findByRawMaterial(material);
                for (RawMaterialProduct rawMaterialProduct : rawMatProdList) {
                    if(!session.isOpen())
                    {
                        session = SessionFactoryUtil.getInstance().getCurrentSession();
                        session.beginTransaction();
                        HibRawMaterialProduct hibRawMaterialProduct = new HibRawMaterialProduct(rawMaterialProduct);
                        session.delete(hibRawMaterialProduct); 
                       
                    }
                    
                }
                session.getTransaction().commit();
                if(!session.isOpen())
                {
                    session = SessionFactoryUtil.getInstance().getCurrentSession();
                    session.beginTransaction();
                    session.delete(hibRawMaterial);                        
                }           

            }
            
            session.getTransaction().commit();

        }
        catch (Exception e) {
            if(session!=null){
                session.getTransaction().rollback();
            }            
            throw new IllegalStateException("Error al eliminar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public RawMaterial findById(int id)
    {
        RawMaterial result = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            HibRawMaterial hibRawMaterial = (HibRawMaterial)session.createCriteria(HibRawMaterial.class).
                    add(Restrictions.eq("rawMaterialId", id)).
                    add(Restrictions.eq("deleted", 0)).uniqueResult();
            if(hibRawMaterial != null)
            {
                result = new RawMaterial(hibRawMaterial.getRawMaterialId(), 
                        hibRawMaterial.getName(), hibRawMaterial.getMessureUnit(), 
                        hibRawMaterial.getAmount(), hibRawMaterial.getPrice(), hibRawMaterial.getDeleted());
            }
            
        }
        catch (Exception e) {
            throw new IllegalStateException("Error al buscar por id",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

        return result;
    }    

    

}
